//
//  PostDetailView.m
//  HeSaid
//
//  Created by MWJ on 15/5/4.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "PostDetailView.h"
#import "commentCell.h"
#import "hotPost.h"
#import "AppDelegate.h"
#import "comment.h"
#import "replyModel.h"
#import "registeredViewController.h"
#import "AllCommentViewController.h"

#define postDetailURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/seekDetails"  //帖子详情url
#define commentURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/comment"  //评论url
#define integralURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/postaddtime"  //积分url
#define commentcountURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/commentcount"  //评论数url

@implementation PostDetailView{
    int kScreenHeight;
    NSMutableArray *postDetailArray;
    NSMutableArray *array;
    AppDelegate *app;
    NSString *placeName;
    NSMutableArray *commentArray;
    NSMutableArray *replyArray1;
    NSMutableArray *replyArray2;
    NSMutableArray *replyArray3;
    NSString *locationString;
    NSMutableArray *commentstr;
    NSMutableArray *replyArray;
    NSMutableArray *replyArr;
    NSMutableArray *contentArray;
    NSString *contentStr;
    commentCell *cell;
    NSString *str;
    NSString *showTimeStr;
    NSString *commcount;
    NSString *colorLength;
    NSString *strIdentifier;
    NSString *strIdentifier1;
    UIAlertView *_alert;
}
- (void)drawRect:(CGRect)rect {
    app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    commentstr = [NSMutableArray array];
    commentArray = [NSMutableArray array];
    postDetailArray=[NSMutableArray array];
    replyArr=[NSMutableArray array];
    replyArray=[NSMutableArray array];
    replyArray1=[NSMutableArray array];
    replyArray2=[NSMutableArray array];
    replyArray3=[NSMutableArray array];
    array=[NSMutableArray array];
    contentArray = [NSMutableArray array];
    if ([app.message_id  isEqual: @"当前位置"]) {
        
    }else{
        NSString *poststr =[NSString stringWithFormat:@"id=%@",app.message_id];
        [self londingPath:postDetailURL Str:poststr];
    }
    self.textF.font=[UIFont fontWithName:@"arial" size:15];
    self.textF.layer.cornerRadius = 5 ;
    self.textF.layer.masksToBounds = YES ;
    self.sendbutton.layer.cornerRadius = 5;
    self.sendbutton.layer.masksToBounds = YES;
    
    
    //自动折行设置
    self.postContent.lineBreakMode = NSLineBreakByCharWrapping;
    self.postContent.numberOfLines = 0;
    self.postContent.layer.borderWidth=0.5;
    self.postContent.layer.borderColor=[[UIColor grayColor]CGColor];
    self.postContent.layer.cornerRadius = 8;
    
    
    strIdentifier1 = @"0";
}

#pragma mark - 请求加载帖子详情信息
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        postDetailArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:postDetailArray waitUntilDone:YES];
    }];
}
-(void)refreshData:(NSMutableArray *)sender{
    
    if (postDetailArray.count<2) {
        for (NSDictionary *dic in postDetailArray) {
            self.postReleaseTime.text=[NSString stringWithFormat:@"%@",dic[@"message_time"]];
            self.postShowTime.text=[NSString stringWithFormat:@"%@",dic[@"message_showtime"]];
            self.postContent.text = [NSString stringWithFormat:@"%@",dic[@"message_content"]];
            showTimeStr=self.postShowTime.text;
            //根据经纬度转换成地名显示
            CLLocationCoordinate2D coordinate;
            coordinate.latitude = [dic[@"message_latitude"] floatValue];
            coordinate.longitude = [dic[@"message_longitude"] floatValue];
            CLLocation *newLocation=[[CLLocation alloc]initWithLatitude:coordinate.latitude longitude: coordinate.longitude];
            CLGeocoder *geocoder=[[CLGeocoder alloc] init];
            [geocoder reverseGeocodeLocation:newLocation
                           completionHandler:^(NSArray *placemarks,
                                               NSError *error){
                               CLPlacemark *placemark=[placemarks objectAtIndex:0];
                               placeName=[NSString stringWithFormat:@"%@%@%@",placemark.locality,placemark.subLocality,placemark.thoroughfare];
                               self.postReleasePlace.text=[NSString stringWithFormat:@"%@",placeName];
                               
                           }];
        }
    }else{
        for (NSDictionary *dic in postDetailArray[0]) {
            self.postReleaseTime.text=[NSString stringWithFormat:@"%@",dic[@"message_time"]];
            self.postShowTime.text=[NSString stringWithFormat:@"%@",dic[@"message_showtime"]];
            self.postContent.text = [NSString stringWithFormat:@"%@",dic[@"message_content"]];
            showTimeStr=self.postShowTime.text;
            //根据经纬度转换成地名显示
            CLLocationCoordinate2D coordinate;
            coordinate.latitude = [dic[@"message_latitude"] floatValue];
            coordinate.longitude = [dic[@"message_longitude"] floatValue];
            CLLocation *newLocation=[[CLLocation alloc]initWithLatitude:coordinate.latitude longitude: coordinate.longitude];
            CLGeocoder *geocoder=[[CLGeocoder alloc] init];
            [geocoder reverseGeocodeLocation:newLocation
                           completionHandler:^(NSArray *placemarks,
                                               NSError *error){
                               CLPlacemark *placemark=[placemarks objectAtIndex:0];
                               placeName=[NSString stringWithFormat:@"%@%@%@",placemark.locality,placemark.subLocality,placemark.thoroughfare];
                               self.postReleasePlace.text=[NSString stringWithFormat:@"%@",placeName];
                               
                           }];
        }
    }
    //获取评论信息
    if (postDetailArray.count<2) {
    }else{
        for (NSDictionary *dic1 in postDetailArray[1]){
            comment *co = [[comment alloc]init];
            co.comment_content = dic1[@"comment_content"];
            [contentArray addObject:dic1[@"comment_content"]];
            co.comment_time = dic1[@"comment_time"];
            co.comment_heardPortrait = dic1[@"comment_heardPortrait"];
            co.comment_identifier = dic1[@"comment_identifier"];
            
            [commentArray addObject:co];
            app.AllCommentArray=commentArray;
        }
        
        [self.postDetailTableView reloadData];
    }
}
#pragma mark - 评论tableview返回的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //判断评论数量，超过十条，“查看全部评论与回复”按钮显示，否则隐藏
    if (commentArray.count<10) {
        self.allComment.hidden=YES;
    }else{
        self.allComment.hidden=NO;
    }
    //返回cell的行数
    return commentArray.count;

}

#pragma mark - 评论每行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return 1  + size.height;
}

#pragma mark - 每行cell的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UINib *nib=[UINib nibWithNibName:@"commentCell" bundle:nil];
    [self.postDetailTableView registerNib:nib forCellReuseIdentifier:@"commentCell"];
    static NSString *cellIdentifier=@"commentCell";
    cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    comment *comm = commentArray[indexPath.row];
    cell.timeLabel.text=[NSString stringWithFormat:@"%@",comm.comment_time];
    strIdentifier=[NSString stringWithFormat:@"%@",comm.comment_identifier];

    if ([strIdentifier isEqualToString:@"0"]) {
        cell.contentLabel.text=[NSString stringWithFormat:@"%@",comm.comment_content];
    }
    else{
    //部分字体变颜色
    NSMutableAttributedString *colorStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",comm.comment_content]];
        NSRange range=[comm.comment_content rangeOfString:@":"];
    [colorStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,range.location+1)];//长度
    cell.contentLabel.attributedText = colorStr;
        
    }
    
        NSURL *url = [NSURL URLWithString:comm.comment_heardPortrait];
        cell.tx.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        cell.floor.text=[NSString stringWithFormat:@"%ld",indexPath.row+1];
            return cell;
}

#pragma mark - 评论内容的所在cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (app.user_id==nil||[app.user_id isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登陆" delegate:self cancelButtonTitle:@"去登陆" otherButtonTitles:@"取消", nil];
        _alert=alert;
        [alert show];
    }else{
    NSString *hf = @"回复";
    NSString *l = @"楼:";
    contentStr = [NSString stringWithFormat:@"%@%ld%@",hf,indexPath.row+1,l];
    strIdentifier1 = @"1";
        
    self.textF.text = contentStr;
    }
}

#pragma mark - 获取当下时间
-(void)currentTime{
    NSDate *senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    locationString=[dateformatter stringFromDate:senddate];
}

#pragma mark - 有一条评论成功就显示时间＋1
-(void)londingPath3:(NSString *)path Str3:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData3:) withObject:str waitUntilDone:YES];
    }];
}
-(void)refreshData3:(NSMutableArray *)sender{
}
#pragma mark - "评论"请求数据加载
-(void)londingPath2:(NSString *)path Str2:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        commentstr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData2:) withObject:commentstr waitUntilDone:YES];
    }];
}
-(void)refreshData2:(NSMutableArray *)sender{
    for (NSDictionary *dic1 in commentstr){
    comment *c = [[comment alloc]init];
    c.comment_content = dic1[@"comment_content"];
    c.comment_time = dic1[@"comment_time"];
    c.comment_heardPortrait = dic1[@"comment_heardPortrait"];
    c.comment_identifier=dic1[@"comment_identifier"];
    [commentArray addObject:c];
}
    showTimeStr = [ NSString stringWithFormat:@"%d",([self.postShowTime.text intValue]+1)];
    app.showTime = showTimeStr;
    self.postShowTime.text=showTimeStr;
    NSString *poststr3 =[NSString stringWithFormat:@"message_id=%@&message_showtime=%@",app.message_id,showTimeStr];
    [self londingPath3:integralURL Str3:poststr3];
    [self.postDetailTableView reloadData];
}

#pragma mark - ”查看全部评论与回复“按钮点击事件
- (IBAction)commentButton:(id)sender {
    [app haveView];
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    AllCommentViewController *all = [sb instantiateViewControllerWithIdentifier:@"AllComVC"];
    [app.haveView pushViewController:all animated:YES];
}
#pragma mark - 提示框“确定”事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        //跳转到注册／登陆界面
        [app haveView];
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        registeredViewController *registered = [sb instantiateViewControllerWithIdentifier:@"registeredVC"];
        [app.haveView pushViewController:registered animated:YES];
    }
}

#pragma mark - 键盘的发送按钮事件
- (IBAction)send:(id)sender {
    //调用“评论”接口加载数据
    [self currentTime];
    
    if (app.user_id==nil||[app.user_id isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登陆" delegate:self cancelButtonTitle:@"去登陆" otherButtonTitles:@"取消", nil];
        _alert=alert;
        [alert show];
    }else{
        
    NSString *poststr1 =[NSString stringWithFormat:@"message_id=%@&user_id=%@&comment_content=%@&comment_time=%@&comment_heardPortrait=%@&comment_identifier=%@",app.message_id,app.user_id,self.textF.text,locationString,app.Portrait,strIdentifier1];
        [self londingPath2:commentURL Str2:poststr1];
        strIdentifier1 = @"0";
    NSString *str1 =[NSString stringWithFormat:@"%ld",(unsigned long)commentArray.count];
    int commentarrayint = [str1 intValue];
    int comint = commentarrayint+1;
    NSString *pstr = [NSString stringWithFormat:@"%d",comint];
    NSString *poststr =[NSString stringWithFormat:@"message_id=%@&message_Comment=%@",app.message_id,pstr];
    [self londingPath1:commentcountURL Str1:poststr];
    self.textF.text = @"";
//    self.mainView.frame = CGRectMake(0, self.bounds.size.height-45, self.mainView.bounds.size.width, self.mainView.bounds.size.height);
    [self hide];
            }
}
#pragma mark - 评论数量＋1
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        commcount = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:commcount waitUntilDone:YES];
    }];
}
-(void)refreshData1:(NSMutableArray *)sender{
}
#pragma mark - 键盘隐藏
- (IBAction)hidden:(id)sender {
    [self.textF resignFirstResponder];
    [self.postContent resignFirstResponder];
//    self.mainView.frame = CGRectMake(0, self.bounds.size.height-45, self.mainView.bounds.size.width, self.mainView.bounds.size.height);
    self.textF.text = @"";
}

-(void)hide{
    [self.mainView endEditing:YES];
}

@end
